package tt.dz.appserver.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.jpush.api.JPushClient;
//import cn.jpush.api.common.APIConnectionException;
//import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Message.Builder;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;

import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.GroupPushClient;
import cn.jpush.api.push.model.notification.*;
import com.google.gson.*;
import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.LoggerFactory;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.SMS;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;

import tt.dz.appserver.entity.dto.push.ChargeDto;
import tt.dz.appserver.util.date.DateUtil;
import tt.dz.appserver.util.enums.push.PushBusinessCode;

/**
 * 极光推送帮助类
 * 
 * @author xielf
 *
 */
public class JpushUtils {

	/** 日志信息 */
	private static final Logger LOG = Logger.getLogger("[推送帮助类]:");

	/** jpush_master_secret */
	public final static String jpush_master_secret = "2a4da79b256051ef0f9bc945";

	/** jpush_app_key */
	public final static String jpush_app_key = "66def62fbd5065bce8fbadbf";

	/** jpush_master_secret */
	public final static String jpush_master_secret_iosTest = "a9aad4502845a3b1330579ca";

	/** jpush_app_key */
	public final static String jpush_app_key_iosTest = "42762940fbef89fd89e5ea82";
	
	
	public static final String ALERT = "Test from API Example - alert";

	/**
	 * 推送   
	 * 
	 * @param payload
	 */
	public static void pushMsgByRegId(String regId, String action, Map<String, String> pushMap) {
		//
		// JPushClient jpushClient = new JPushClient(jpush_master_secret,
		// jpush_app_key, 20);
		ClientConfig config = ClientConfig.getInstance();
		Builder builder = Message.newBuilder();
		builder.setMsgContent(action);

		if (pushMap != null) {
			for (String key : pushMap.keySet()) {
				String value = pushMap.get(key);
				builder.addExtra(key, value);
			}
		}
		try {  
//		LOG.info("推送开始0");
		// Setup the custom hostname
//		config.setPushHostName("https://api.jpush.cn");
//		LOG.info("推送开始1");
//		LOG.info("jpush_master_secret = "+jpush_master_secret);
//		LOG.info("jpush_app_key = "+ jpush_app_key);
		JPushClient jpushClient = new JPushClient(jpush_master_secret, jpush_app_key, null, config);
//		LOG.info("推送开始2");
//		LOG.info("推送开始3");
		long time = Math.round(System.currentTimeMillis() / 1000.0) + (2 * 60);// 有效时间为两分钟
		builder.addExtra("timeout", time);

			LOG.info("常规key推送开始");
			PushResult result = jpushClient.sendPush(
					PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(regId))
							.setOptions(Options.newBuilder().setApnsProduction(false).build())
							.setMessage(builder.build()).build());
			LOG.info("常规key推送成功 - " + result);
			
		} catch (APIConnectionException e) {
			LOG.error("连接错误,请稍后重试.", e);
		} catch (APIRequestException e) {
			e.printStackTrace();
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
			try {
				JPushClient jpushClientIos = new JPushClient(jpush_master_secret_iosTest, jpush_app_key_iosTest, null, config);
				LOG.info("IOSkey推送开始");
				PushResult resultIos = jpushClientIos.sendPush(
						PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(regId))
								.setOptions(Options.newBuilder().setApnsProduction(false).build())
								.setMessage(builder.build()).build());
				LOG.info("IOSkey推送成功 - " + resultIos);
			}catch (APIConnectionException e1) {
				LOG.error("连接错误,请稍后重试.", e1);
			}catch(APIRequestException iosE) {
				iosE.printStackTrace();
				LOG.error("iosE Error response from JPush server. Should review and fix it. ", iosE);
				LOG.info("HTTP Status: " + iosE.getStatus());
				LOG.info("Error Code: " + iosE.getErrorCode());
				LOG.info("Error Message: " + iosE.getErrorMessage());
				LOG.info("Msg ID: " + iosE.getMsgId());
			}
			
			
		}
	}

	public static void testSendPushWithCustomConfig() {
		ClientConfig config = ClientConfig.getInstance();
		// Setup the custom hostname
		config.setPushHostName("https://api.jpush.cn");

		JPushClient jpushClient = new JPushClient(jpush_master_secret, jpush_app_key, null, config);

		// For push, all you need do is to build PushPayload object.
		PushPayload payload = buildPushObject_all_all_alert();

		try {
			PushResult result = jpushClient.sendPush(payload);
			LOG.info("Got result - " + result);

		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);

		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
	}

	public static PushPayload buildPushObject_all_all_alert() {
		return PushPayload.alertAll(ALERT);
	}

	public static void main1(String[] args) {
		System.out.println(Math.round(System.currentTimeMillis() / 1000.0) + 2 * 60);
		System.out.println(System.currentTimeMillis());
	}

	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {

//		ChargeDto dto = new ChargeDto();
//		dto.setActionType("1");
//		dto.setChargerId("123");
//		dto.setChargeSn("321");
//		dto.setPlugNo("1");
//		LOG.info("1 " + 1);
//		LOG.error(2);
//		LOG.debug(DateUtil.getDate());
//		LOG.debug(3);
//		LOG.warn("4");
//		Map<String, String> pushData = ReflectUtils.objectParseMap(dto);
//		Map<String, String> pushMap = new HashMap<String, String>();
//		pushMap.put("action", PushBusinessCode.CHARGE.getCode());
//		pushMap.put("data", JSON.toJSONString(pushData));
//		System.out.println(JSON.toJSONString(pushMap));
//		// 08027d2100f 18071adc030d728d2f6
//		JpushUtils.pushMsgByRegId("080a604889c", "您在通威国际中心的1号桩已开始充电", pushMap);
		
		
		ChargeDto dto = new ChargeDto();
		dto.setActionType("1");
		dto.setChargerId("123");
		dto.setChargeSn("321");
		dto.setPlugNo("1");
		Map<String, String> pushData = ReflectUtils.objectParseMap(dto);
		Map<String, String> pushMap = new HashMap<String, String>();
		pushMap.put("action", PushBusinessCode.CHARGE.getCode());
		pushMap.put("data", JSON.toJSONString(pushData));
		System.out.println(JSON.toJSONString(pushMap));
		// 08027d2100f 18071adc030d728d2f6
		JpushUtils.pushMsgByRegId("13165ffa4e28d90f662", "您在七龙珠中心的1号桩已开始充电", pushMap);//170976fa8aa0c36a6ac  13165ffa4e28d90f662
	}

}
